package com.hyt.it.ogt.kq.service.gov.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.hyt.core.util.UUIDUtils;
import com.hyt.it.ogt.kq.common.config.ConfigManager;
import com.hyt.it.ogt.kq.common.config.exception.KqException;
import com.hyt.it.ogt.kq.common.gov.constant.ResponseCode;
import com.hyt.it.ogt.kq.common.gov.constant.StringCodeEnum;
import com.hyt.it.ogt.kq.common.gov.utils.HuaweiCloudObsUtil;
import com.hyt.it.ogt.kq.service.gov.model.entity.CandidateTicket;
import com.hyt.it.ogt.kq.service.gov.service.IAdmissionCreateService;
import com.obs.services.model.PutObjectResult;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 生成准考证 服务实现类
 * </p>
 *
 * @author huangyh
 * @since 2021-03-08
 */
@Service
@Slf4j
public class AdmissionCreateServiceImpl implements IAdmissionCreateService {

    @Resource
    private ConfigManager configManager;

    /**
     * 上传华为云
     * @return
     */
    @Override
    public void uploadToCloud(List<CandidateTicket> candidateTicketList ,String taskCode){
        for(CandidateTicket ticket : candidateTicketList) {
            this.uploadToCloud(ticket, taskCode);
        }
    }

	public void uploadToCloud(CandidateTicket ticket, String taskCode) {
		// 创建一个临时文件
		File file = new File(ticket.getPath());
		file.deleteOnExit();
		try {
			String name = StringUtils.join(configManager.getCloudRootPath(), taskCode, "/admissionTicket/", UUIDUtils.newSortUUID(), StringCodeEnum.FILE_SUFFIX_DOT_PDF.getCode());
			PutObjectResult putObjectResult = HuaweiCloudObsUtil.uploadFileResult(name, new FileInputStream(file));
			if (null != putObjectResult) {
				ticket.setPath(putObjectResult.getObjectKey());
				ticket.setDelFlag(false);
			} else {
				log.info("# 准考证上传华为云失败：{}#{}", ticket.getCandidateId(), JSON.toJSONString(putObjectResult));
			}
		} catch (FileNotFoundException e) {
			throw new KqException(ResponseCode.TICKET_EXPORT_EXCEPTION.getCode(), ResponseCode.TICKET_EXPORT_EXCEPTION.getMsg());
		}
	}
}
